package com.alex.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 认证过滤器
 *
 * @author Alex.shu
 */
public class AuthFilter extends ZuulFilter {

    @Autowired
    private BasicConfig basicConfig;

    public AuthFilter() {
        super();
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    public boolean shouldFilter() {
        return true;
    }

    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        String apiWhiteStr = basicConfig.getApiWhiteStr();

        // 白名单, 则直接放过拦截
        List<String> whiteApiGroup = Arrays.asList(apiWhiteStr.split(","));
        String requestURI = currentContext.getRequest().getRequestURI();
        if (whiteApiGroup.contains(requestURI)) {
            return null;
        }

        // path uri处理
        for (String whiteAPi : whiteApiGroup) {
            if (whiteAPi.contains("{}") && whiteAPi.contains("()")) {
                if (whiteAPi.split("/").length == requestURI.split("/").length) {
                    String reg = whiteAPi.replaceAll("\\{.*}", ".*{1,}");
                    Pattern compile = Pattern.compile(reg);
                    Matcher matcher = compile.matcher(requestURI);
                    if (matcher.find()) {
                        return null;
                    }
                }
            }
        }

        return null;
    }
}
